package com.pomr.controller.sys;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pomr.model.sys.User;
import com.pomr.service.sys.LoginService;
import com.pomr.util.common.CallMessage;
import com.pomr.util.common.CommonData;
import com.pomr.util.common.JWT;
import com.pomr.util.common.ResponseData;
import com.pomr.util.exception.LoginException;


@Controller
public class LoginController {
	@Autowired
	private LoginService loginService;
	/**
	 * 登录入口
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(){
		return "login";
	}
	
	@ResponseBody//作用是将返回的对象作为响应，发送给页面
	@RequestMapping(value="/finduser",method=RequestMethod.GET)
	public ModelAndView findUsers(ModelAndView m){
		m.setViewName("health/data");
		return m;
	}
	
	@RequestMapping(value="/healthdata",method=RequestMethod.POST)
	@ResponseBody
	public ModelAndView doHealthRecorddata(ModelAndView m, @RequestBody Map<String,String> map){
		m.setViewName("health/"+map.get("tabid"));
		return m;
	}
	
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(User u, HttpServletRequest request,Model model,HttpSession session){
		System.out.println("正在登陆");
		if(null != u){
			//通过用户名、密码查询用户
			try {
				u = loginService.getUserOfLogin(u);
			} catch (Exception e) {
				e.printStackTrace();
				session.setAttribute("msg", "查找用户异常");//添加标志位
				return "login";
			}
			if(null == u){
				session.setAttribute("msg", "找不到该用户");//添加标志位
				return "login";
			}
			session.setAttribute("user", u);
			
		}else{
			session.setAttribute("msg", "用户信息错误");//添加标志位
			return "login";
		}
		System.out.println("-------------------------------");
		System.out.println(u.getRole().getRoleName());
		return "main/main";
	}
	
	/**
	 * 通过接口登录
	 * 
	 * @return
	 */
	@RequestMapping(value = "/inter/login", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData loginOfInter(@RequestBody Map<String, String> map) throws Exception {
		String uname = map.get("uname").toString().trim();
		String pwd = map.get("pwd").toString().trim();
		User u = new User();
		u.setUname(uname);
		u.setPassword(pwd);
		ResponseData pd = null;
		u = loginService.getUserOfLogin(u);
		if (null == u) {
			pd = ResponseData.custom("用户不存在");
		} else {
			// 将延迟加载内容置空 不然json转换报错
			// u.setRole(null);
			// u.setAgency(null);
			if (u.getAgency() != null) {
				u.getAgency().setCreateUser(null);
				u.getAgency().setCoutry(null);
			}
			// 给用户jwt加密生成token
			Map<String, Object> config = (Map<String, Object>) CommonData.data.get("config");
			Long tokentime = Long.valueOf(config.get("token.date").toString());// 获取有效时间
			String token = JWT.sign(u, tokentime);
			if (token != null) {
				System.out.println("token:" + token);
				System.out.println(JWT.unsign(token, User.class));
			} else {
				System.out.println("token:null");
			}
			pd = ResponseData.ok();
			// 封装成对象返回给客户端
			pd.putDataValue("userid", u.getId());
			pd.putDataValue("token", token);

			pd.putDataValue("user", u);
			long currentTime = System.currentTimeMillis();

			pd.putDataValue("duetime", (currentTime += tokentime));// 设置过期时间

			//获取用户权限信息
			pd.putDataValue("effect", loginService.searchEffectsByUserId(u.getId()));
			//将菜单表信息存储的本地
			pd.putDataValue("commondata", CommonData.data);
		}
		return pd;
	}
	
	
	/**
	 * 注册用户
	 * @param uname 用户名
	 * @param name 姓名
	 * @param password 密码
	 * @return
	 */
	@RequestMapping(value="/registeruser",method=RequestMethod.POST)
	public String registerUser(@RequestParam("register_uname")String uname,@RequestParam("register_name")String name,
			@RequestParam("register_pwd")String password,Model model, HttpSession session){
		User u = new User();
		u.setName(name);
		u.setUname(uname);
		u.setPassword(password);
		if(null != u){
			try {
				if(loginService.registerUser(u)){
					session.setAttribute("msg", "注册成功");//添加标志位
				}else{
					session.setAttribute("msg", "注册失败,数据插入失败");//添加标志位
				}
			} catch (Exception e) {
				e.printStackTrace();
				session.setAttribute("msg", "注册失败，信息插入异常");//添加标志位
			}
		}
		return "login";
	}
	
	/**
	 * 验证用户名唯一性
	 * @return
	 */
	@RequestMapping(value="/testuname",method=RequestMethod.POST)
	@ResponseBody
	public CallMessage testUname(@RequestBody Map<String, String> map){
		CallMessage cm = null;
		try {
			if(loginService.testUname(map.get("uname").toString().trim())){//已存在
				cm = new CallMessage("true", "");
			}else{
				cm = new CallMessage("false", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			cm = new CallMessage("false", "");
		}
		
		return cm;
	}
	
	
	/**
	 * 通过用户名、邮箱验证验证账户
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/callpwd",method=RequestMethod.POST)
	@ResponseBody
	public CallMessage callPwdIsTrue(@RequestBody Map<String, String> map){
		CallMessage cm = null;
		String uname = map.get("uname").toString().trim();
		String email = map.get("email").toString().trim();
		try {
			if(loginService.testUnameByEmail(uname, email)){//已存在
				cm = new CallMessage("true", "");
			}else{
				cm = new CallMessage("false", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			cm = new CallMessage("false", "");
		}
		
		return cm;
	}
	
	/**
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/changepwd",method=RequestMethod.POST)
	@ResponseBody
	public CallMessage changePwd(@RequestBody Map<String, String> map){
		CallMessage cm = null;
		String uname = map.get("uname").toString().trim();
		String pwd = map.get("pwd").toString().trim();
		try {
			if(loginService.changePwd(uname, pwd)){//已更新
				cm = new CallMessage("true", "");
			}else{
				cm = new CallMessage("false", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			cm = new CallMessage("false", "");
		}
		
		return cm;
	}
}
